#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cstring>
#include <sys/types.h>
#include<sys/wait.h>
#include<unistd.h>

const char* GetUserName()
{
  const char* name = getenv("USER");
  return name == NULL ? "None" : name;
}

const char* GetHostName()
{
  const char* hostname = getenv("HOSTNAME");
  return hostname == NULL ? "None" : hostname;
}

const char* GetPWD()
{
  const char* pwd = getenv("PWD");
  return pwd == NULL ? "None" : pwd;
}


/////  /a/b/c
std::string DirName(const char* pwd)
{
  #define SLASH "/"
  std::string dir = pwd;
  if(dir == SLASH) return SLASH;
  auto pos = dir.rfind(SLASH);
  if(pos == std::string::npos) return "BUG";
  return dir.substr(pos + 1);
}

void PrintCommdPrompt()
{
  #define COMMAND_SIZE 1024
  #define FORMAT "[%s@%s %s]"
  
  char prompt[COMMAND_SIZE];
  //snprintf(prompt, COMMAND_SIZE, FORMAT, GetUserName(), GetHostName(), GetPWD());
  snprintf(prompt, COMMAND_SIZE, FORMAT, GetUserName(), GetHostName(), DirName(GetPWD()).c_str());
  printf("%s", prompt);
  fflush(stdout);
}

bool GetCommandLine(char* out, int size)
{
  char* c = fgets(out, size, stdin);   //很多系统调用都是用c语言做接口，getline等其他c++接口也能用，但最好用c语言
  if(c == NULL) return false;
  
  out[strlen(out) - 1] = 0; //清理\n   ????????
  if(strlen(out) == 0) return false;

  return true;
}

  //shell的全局定义
  #define MAXARGC 128
  char* g_argv[MAXARGC];
  int g_argc = 0;
void CommandParse(char* commandline)
{

  #define SEP " "

  g_argc = 0;
  g_argv[g_argc++] = strtok(commandline, SEP);

  while((bool)(g_argv[g_argc++] = strtok(NULL, SEP)));

  g_argc--;

}

void PrintArgv()
{
    //for(int i = 0; g_argv[i]; i++)
    for(int i = 0; i < g_argc; i++)
    {
        printf("argv[%d]->%s\n", i, g_argv[i]);
    }
    printf("argc: %d\n", g_argc);
}

void Execute()
{
  pid_t id = fork();
  if(id == 0)
  {
    execvp(g_argv[0], g_argv);
    exit(1);
  }
  
  pid_t retid = waitpid(id, NULL, 0); 
  (void)retid;
  
}


int main()
{
  while(1)
  {
      //1.输出命令行指令
      PrintCommdPrompt();
      
      //2. 获得用户输入的指令
      char commandline[COMMAND_SIZE];
      if(!GetCommandLine(commandline, sizeof(commandline)))
      continue;
  
      //printf("echo: %s", commandline);
      //3. 命令行分析"ls -a -l" -> "ls" "-a" "-l"
      CommandParse(commandline);
     // PrintArgv();

      //4. 执行命令
      Execute();
  }
  return 0;
}
